package essentials;

public class Controller {

    private Model model = Model.createInitialModel();
    private Logic logic = Logic.createLogic();
    private SimpleGUI view;
    private ModelViewHelper mvh;

    public Controller() {
    }

    public void initializeModel() {
        model.initModel();
    }

    void setView(SimpleGUI view) {
        this.view = view;
    }

    private ModelViewHelper getMVH() {

        if (mvh == null) {
            mvh = new ModelViewHelper(view, model);
        }
        return mvh;
    }

    public void modelToView() {
        getMVH().modelToView();
    }

    public void viewToModel() {
        getMVH().viewToModel();
    }

    private String getValidationErrorsForViewInput() {

        String err = "";

        if (getMVH().getTextFromGewichtTF().isEmpty()) {
            err = err + "gewichtTF().isEmpty" + "\n";
//            isValid = false;
        }
        if (getMVH().getTextFromGroesseTF().isEmpty()) {
            err = err + "groesseTF().isEmpty" + "\n";
//            isValid = false;
        }
        if (!UtilsToSort.stringIsValidDouble(getMVH().getTextFromGewichtTF())) {
            err = err + "gewichtTF is not a valid Double" + "\n";
//            isValid = false;
        }
        if (!UtilsToSort.stringIsValidDouble(getMVH().getTextFromGroesseTF())) {
            err = err + "groesseTF() is not a valid Double" + "\n";
//            isValid = false;
        }

        System.out.println("err:" + err);
        return err;
    }

    public void doSomethingImportant() {

        if (getValidationErrorsForViewInput().isEmpty()) {

            viewToModel();
            logic.updateOperationLog(model);

            String resultString = model.getFullInput();

            view.getOutputTA().setText(resultString);
        } else {
            model.setNewInput("invalid Input!");
            logic.updateOperationLog(model);
            view.getOutputTA().setText(model.getFullInput());
        }
    }

    public void berechneBmiAnfrage() {
        if (getValidationErrorsForViewInput().isEmpty()) {
            viewToModel();
            Double bmi = logic.berechneBMI(model);
            model.setBmi(bmi);
            getMVH().modelToView();
        } else {
            model.setNewInput("invalid Input!");
            logic.updateOperationLog(model);
            view.getOutputTA().setText(model.getFullInput());
        }
    }
}
